	/*
	 * Copyright (C) <2011>  <Matthew Dickinson>
	 * This program is free software: you can redistribute it and/or modify
	 * it under the terms of the GNU General Public License as published by
	 * the Free Software Foundation, either version 3 of the License, or
	 * (at your option) any later version.
	 *
	 * This program is distributed in the hope that it will be useful,
	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	 * GNU General Public License for more details.
	 *
	 * You should have received a copy of the GNU General Public License
	 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
	*/

	package com.pulsarwebdevelopment.concordance.plugins;

	import java.io.File;
	import java.util.ArrayList;

	import com.pulsarwebdevelopment.concordance.Concordance;
	import com.pulsarwebdevelopment.concordance.Tools;

	/**
	 * Processes text file and highlights all unique words.
	 * @author Matthew Dickinson
	 * Last updated: 9/23/2009
	 */
	public class UniqueGraphicalFillInTheBlanks extends UniqueX{

		private Concordance uniqueList;
		private Concordance pairList;
		private Concordance tripleList;
		private ArrayList<String> uniqueWords;
		private ArrayList<String> pairWords;
		private ArrayList<String> tripleWords;
		boolean wantUnique;
		boolean wantPairs;
		boolean wantTriples;

		private int wordId = 0;
		
		private int difficulty;
		
		//@Override
		public void go(Object[] args) {
			int concIndex = (Integer) args[0];
			readFile = (File) args[1];
			exportFile = (File) args[2];
			wantUnique = (Boolean) args[3];
			wantPairs = (Boolean) args[4];
			wantTriples = (Boolean) args[5];
			difficulty = Integer.parseInt(args[6].toString());

			if(wantUnique){
				uniqueList = new Concordance(concIndex);
				//uniqueList.setSubset(1);
				uniqueWords = uniqueList.getWordSet(1);
			}
			if(wantPairs){
				pairList = new Concordance(concIndex);
				//pairList.setSubset(2);
				pairWords = pairList.getWordSet(2);
			}
			if(wantTriples){
				tripleList = new Concordance(concIndex);
				//tripleList.setSubset(3);
				tripleWords = tripleList.getWordSet(3);
			}

			parseFile();
		}

		//@Override
		public void plug(PluginScreen screen) {
			screen.setTitleText("Graphical Fill in the Blank", 
					"Sets up fill in the blanks for sets of words from a document. " +
					"This application lets you choose the difficulty (number of letters you need to fill in before your answer is considered complete." +
					"Fill the words and press tab to continue to the next word and see if you were correct on the previous word.");
			screen.giveConcList("Choose the concordance to use.");
			screen.giveFileBrowser(FileBrowser.FileType.TEXT, "Choose the file to process.");
			screen.giveFileBrowser(FileBrowser.FileType.HTML, "Choose the file (.html) to output results to.");
			String[] values = {"Unique Words", "Word Pairs", "Word Triples"};
			screen.giveCheckBoxes("Choose which set(s) of words you want to have to fill in", values);
			screen.giveTextField("Enter the number of charaters that you will need to complete for each word.");
		}

		@Override
		public String getHeader() {
			return "<html>\n" +
			"<head>\n" +
			"<style type='text/css'>\n" + 
			"        .wrong {background-color:red}\n" + 
			"        .right {background-color: green}\n" + 
			"        .answer {display: none}\n" + 
			"        .incomplete{background-color: yellow}\n" + 
			"        #control-panel{position: fixed; top: 0px; background-color: gray; width: 100%}\n" + 
			"        #control-panel-counts {padding-left: 42%; }\n" + 
			"        #main-panel{ padding-top: 10px}\n" + 
			"        </style>\n" + 
			"        <script type='text/javascript'>\n" + 
			"          var uniqueNum;\n" + 
			"          //var uniqueNumWro;\n" + 
			"          var pairNum;\n" + 
			"          //var pairNumRight;\n" + 
			"          var tripleNum;\n" + 
			"          //var tripleNumRight;\n" + 
			"        \n" + 
			"          var totalCount = 0;\n" + 
			"          var completedCount = 0;\n" + 
			"        \n" + 
			"          var difficulty = " + difficulty + ";" +  
			"        \n" + 
			"          var begTime = new Date();\n" + 
			"        \n" + 
			"          String.prototype.trim = function(){\n" + 
			"            return this.substring(0, this.lastIndexOf(' '));\n" + 
			"          }\n" + 
			"        \n" + 
			"          function runCheck(element) {\n" + 
			"            var enteredValue = element.value;\n" + 
			"            var id = element.id;\n" + 
			"            var correctVal = document.getElementById(id + '_answer').innerHTML;\n" + 
			"        \n" + 
			"            var substrLength = (difficulty > correctVal.length)? correctVal : difficulty;\n" + 
			"        \n" + 
			"            if (enteredValue.length >= substrLength) {\n" + 
			"              \n" + 
			"              if (enteredValue.substring(0, substrLength).toUpperCase() == correctVal.substring(0, substrLength).toUpperCase()) {\n" + 
			"                //alert('you got a match');\n" + 
			"                switchWordStatus(element, 'right');\n" + 
			"                \n" + 
			"              }else{\n" + 
			"                switchWordStatus(element, 'wrong');\n" + 
			"        \n" + 
			"                var wrongCount = document.getElementById('wrong-count').innerHTML * 1;\n" + 
			"                wrongCount++;\n" + 
			"                document.getElementById('wrong-count').innerHTML = wrongCount;\n" + 
			"              } \n" + 
			"        \n" + 
			"              //display the correct word. (Both for incorrect and correct answers)\n" + 
			"              element.value = correctVal;\n" + 
			"        \n" + 
			"              //increment the count of items done\n" + 
			"              completedCount++;\n" + 
			"              //if all are competed, display the final time\n" + 
			"              if(completedCount == totalCount){\n" + 
			"                showFinish();\n" + 
			"              }\n" + 
			"            }else{\n" + 
			"              switchWordStatus(element, 'incomplete');\n" + 
			"            }\n" + 
			"          }\n" + 
			"        \n" + 
			"          function setUpNums(){\n" + 
			"            totalCount = document.getElementsByTagName('input').length;\n" + 
			"            document.getElementById('total-count').innerHTML = totalCount;\n" + 
			"          }\n" + 
			"        \n" + 
			"          function showFinish(){\n" + 
			"            var endTime = new Date();\n" + 
			"            var elapsedTime = endTime - begTime;\n" + 
			"            elapsedTime = Math.floor(elapsedTime / 1000);\n" + 
			"            var elapsedMins = Math.floor(elapsedTime / 60)\n" + 
			"            var elapsedSecs = elapsedTime % 60;\n" + 
			"        \n" + 
			"            alert('You completed this page in ' + elapsedMins + ' minutes and ' + elapsedSecs + ' seconds.');\n" + 
			"          }\n" + 
			"        \n" + 
			"          function switchWordStatus(element, status){\n" + 
			"            element.className = element.className.replace(' right', '')\n" + 
			"                          .replace(' wrong', '')\n" + 
			"                          .replace(' incomplete', '');\n" + 
			"            element.className += ' ' + status;\n" + 
			"          }\n" + 
			"        </script>\n" + 
			"     </head>\n" + 
			"	  <body onload='setUpNums()'>\n" + 
			"        <div id='control-panel'><span id='control-panel-counts'>Wrong: <span id='wrong-count'>0</span> Total: <span id='total-count'>0</span></span></div>\n" + 
			"        <div id='main-panel'>";
		}

		@Override
		public String getFooter() {
			return "</body></html>";
		}

		@Override
		public String getParagrapStart() {
			return "<p>";
		}

		@Override
		public String getParagrapEnd() {
			return "</p>\n";
		}

		@Override
		public String handleWord(String word){
			wordId++;
			
			String capWord = Tools.capitalize(word);

			/*System.out.println("   " + tripleList.hasWord(Tools.capitalize(word)) + " " + pairList.hasWord(Tools.capitalize(word)) + " " + uniqueList.hasWord(Tools.capitalize(word)));*/
			
			//run these checks backwards. As triples are those that appear 3 times, 
			// these words should show up more often than words pairs, etc...
			if(wantTriples && tripleWords.contains(capWord)){	//tripleList.hasWord(Tools.capitalize(word))){
				return "<input type='text' class='triples ' id='" + wordId + "' size='" + word.length() + "' onblur='runCheck(this)'/><span class='answer' id='"+ wordId +"_answer'>" +  word + "</span>";						
			}
			if(wantPairs && pairWords.contains(capWord)){	//pairList.hasWord(Tools.capitalize(word))){
				return "<input type='text' class='pairs ' id='" + wordId + "' size='" + word.length() + "' onblur='runCheck(this)'/><span class='answer' id='"+ wordId +"_answer'>" +  word + "</span>";				
			}
			if(wantUnique && uniqueWords.contains(capWord)){	//uniqueList.hasWord(Tools.capitalize(word))){
				return "<input type='text' class='unique ' id='" + wordId + "' size='" + word.length() + "' onblur='runCheck(this)'/><span class='answer' id='"+ wordId +"_answer'>" +  word + "</span>";					
			}

			return word;
		}

	}


